package com.myjava.managesystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myjava.managesystem.common.R;
import com.myjava.managesystem.entity.Employee;
import com.myjava.managesystem.service.EmployeeService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;


    @GetMapping("/{id}")
    public R<Employee> getEmp(@PathVariable Long id) {
        Employee emp = employeeService.getById(id);
        return R.success(emp);
    }

    @GetMapping("/page")
    public R<IPage> getPage(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestParam(required = false) String name) {
        Page<Employee> p = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Employee::getName, name);
        wrapper.orderByDesc(Employee::getUpdateTime);
        IPage<Employee> iPage = employeeService.page(p, wrapper);
        return R.success(iPage);
    }


    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody(required = false) Employee employee) {
        log.info(employee.toString());
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @PostMapping
    public R<String> insertEmp(HttpServletRequest request, @RequestBody Employee employee) {
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        if (employeeService.save(employee)) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }
    }


    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        return employeeService.empLogin(request, employee.getUsername(), employee.getPassword());

    }

    @PostMapping("/logout")
    public R<Employee> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success(null);
    }
}
